﻿using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.ComponentModel.Design;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell;

namespace Personal.BuildAsSilverlight4
{
    /// <summary>
    /// This is the class that implements the package exposed by this assembly.
    ///
    /// The minimum requirement for a class to be considered a valid package for Visual Studio
    /// is to implement the IVsPackage interface and register itself with the shell.
    /// This package uses the helper classes defined inside the Managed Package Framework (MPF)
    /// to do it: it derives from the Package class that provides the implementation of the 
    /// IVsPackage interface and uses the registration attributes defined in the framework to 
    /// register itself and its components with the shell.
    /// </summary>
    // This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is
    // a package.
    [PackageRegistration(UseManagedResourcesOnly = true)]
    // This attribute is used to register the informations needed to show the this package
    // in the Help/About dialog of Visual Studio.
    [InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)]
    // This attribute is needed to let the shell know that this package exposes some menus.
    [ProvideMenuResource("Menus.ctmenu", 1)]
    [Guid(GuidList.guidBuildAsSilverlight4PkgString)]
    public sealed class BuildAsSilverlight4Package : Package
    {
        #region Properties
        public DTE2 DteInstance
        {
            get { return GetService(typeof(DTE)) as DTE2; }
        }

        public UIHierarchy SolutionExplorer
        {
            get { return DteInstance.ToolWindows.SolutionExplorer; }
        }

        public OutputWindowPane CustomOutputWindowPane
        {
            get
            {
                OutputWindowPane outputWindowPane = null;
                try
                {
                    outputWindowPane = DteInstance.ToolWindows.OutputWindow.OutputWindowPanes.Item(Constants.ADDIN_NAME);
                }
                catch
                {
                    outputWindowPane = DteInstance.ToolWindows.OutputWindow.OutputWindowPanes.Add(Constants.ADDIN_NAME);
                }
                return outputWindowPane;
            }
        }
        #endregion

        internal void ShowMessage(string title, string message)
        {
            var uiShell = (IVsUIShell)GetService(typeof(SVsUIShell));
            var clsid = Guid.Empty;
            int result;
            ErrorHandler.ThrowOnFailure(uiShell.ShowMessageBox(
               0,
               ref clsid,
               title,
               message,
               string.Empty,
               0,
               OLEMSGBUTTON.OLEMSGBUTTON_OK,
               OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST,
               OLEMSGICON.OLEMSGICON_INFO,
               0,        // false
               out result));
        }


        /////////////////////////////////////////////////////////////////////////////
        // Overriden Package Implementation
        #region Package Members

        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initilaization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
            base.Initialize();

            // Add our command handlers for menu (commands must exist in the .vsct file)
            var mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if (null != mcs)
            {
                // Create the command for the menu item.
                var menuCommandID = new CommandID(GuidList.guidBuildAsSilverlight4CmdSet, (int)PkgCmdIDList.cmdidBuildAsSilverlight4);
                var menuItem = new MenuCommand(MenuItemCallback, menuCommandID);
                mcs.AddCommand(menuItem);
            }
        }
        #endregion

        /// <summary>
        /// This function is the callback used to execute a command when the a menu item is clicked.
        /// See the Initialize method to see how the menu item is associated to this function using
        /// the OleMenuCommandService service and the MenuCommand class.
        /// </summary>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            var items = SolutionExplorer.SelectedItems as Array;
            try
            {
                dynamic selectedItem = items.GetValue(0);
                selectedItem = selectedItem.Object;
                if (selectedItem.Saved)
                {
                    if (selectedItem.FileName.EndsWith("csproj"))
                    {
                        SetWorkingDirectory(selectedItem);
                        var helper = new BuildHelper();
                        var silverlightProjectFile = helper.CreateSilverlightProject(selectedItem.FileName);
                        string buildOutput = helper.BuildSilverlightProject(silverlightProjectFile);
                        CustomOutputWindowPane.ClearAndDisplay(buildOutput);
                    }
                }
                else
                {
                    CustomOutputWindowPane.ClearAndDisplay("Please save the project before building.");
                }
            }
            catch (Exception ex)
            {
                CustomOutputWindowPane.ClearAndDisplay("Unknown error occurred please contact the developer.");
                ExceptionHandler.WriteToLog(ex);
            }
            finally
            {
                CustomOutputWindowPane.Activate();
            }
        }

        private static void SetWorkingDirectory(object selectedItem)
        {
            string projectFilesPath = ((dynamic)selectedItem).FileName;
            var workingDirectory = projectFilesPath.Substring(0, projectFilesPath.LastIndexOf("\\"));
            Directory.SetCurrentDirectory(workingDirectory);
        }
    }
}

